<template>
  <div id="goods-list">
    <!-- switch parent border: <el-switch v-model="parentBorder" /> switch child
  border: <el-switch v-model="childBorder" /> -->
    <el-table :data="tableData" :border="parentBorder" style="width: 100%">
      <el-table-column type="expand">
        <template #default="props">
          <div m="4">
            <label for="">
              商品ID {{ props.row.id }}<br />
              所属分类 {{ props.row.category }}<br />
              创建时间 {{ moment(props.row.ctime).format('YYYY-MM-DD HH:mm:ss') }}<br />
              商品销量 {{ props.row.sellCount }}份<br />
              商品图片
              <img
                style="width: 100px"
                :src="`http://127.0.0.1:5000/upload/imgs/goods_img/${props.row.imgUrl}`"
                alt=""
              /><br />
              商品名称 {{ props.row.name }}<br />
              商品价格 ￥{{ props.row.price }}<br />
              商品评价 {{ props.row.rating }}分<br />
              商品描述 {{ props.row.goodsDesc }}
            </label>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="name"> </el-table-column>
      <el-table-column label="所属分类" prop="category" />
      <el-table-column label="商品价格" prop="price" />
      <el-table-column label="商品图片" prop="imgUrl">
        <template #default="scope">
          <img :src="`http://127.0.0.1:5000/upload/imgs/goods_img/${scope.row.imgUrl}`" alt="" />
        </template>
      </el-table-column>
      <el-table-column label="商品描述" prop="goodsDesc" />
      <el-table-column label="操作" prop="">
        <template #default="scope">
          <el-button plain type="primary" @click="edit(scope.row.id)"> 编辑 </el-button>
          <el-button plain @click="open(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="currentPage4"
      v-model:page-size="pageSize4"
      :page-sizes="[5, 10, 15]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="20"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 弹窗 -->
    <el-dialog v-model="dialogFormVisible" title="编辑商品" width="500">
      <el-form :model="form">
        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="所属分类" :label-width="formLabelWidth">
          <el-select
            v-for="(item, index) in categories"
            :key="index"
            v-model="form.category"
            placeholder="选择分类"
          >
            <el-option
              v-for="(ele, index) in item"
              :key="index"
              :label="ele.cateName"
              :value="ele.cateName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" :label-width="formLabelWidth">
          <el-input v-model="form.price" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品描述" :label-width="formLabelWidth">
          <el-input v-model="form.goodsDesc" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品图片" :label-width="formLabelWidth">
          <el-upload
            action="http://127.0.0.1:5000/goods/goods_img_upload"
            method="post"
            list-type="picture-card"
            :on-success="handleSuccess"
            :auto-upload="true"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            v-model:file-list="fileList"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="confirmEdit()"> Confirm </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import {
  fetchGoodsList,
  fetchGoodsDel,
  fetchGoodsCategories,
  fetchGoodsEdit,
} from '../api/goods/index'
import moment from 'moment'
import { ElMessage, ElMessageBox } from 'element-plus'

import { Plus } from '@element-plus/icons-vue'

import type { UploadProps } from 'element-plus'

const parentBorder = ref(false)
// const childBorder = ref(false)
const tableData = ref([])
watch(tableData,()=>{
  // console.log(tableData);

})
import type { ComponentSize } from 'element-plus'
const pageSize4 = ref(5)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
//修改图片的imgUrl
const imgUrl = ref('')

const categories = ref(null)
watch(categories, () => {})
// const dialogTableVisible = ref(false)
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

const fileList = ref([])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
//上传成功，保存url
const handleSuccess = (response, file, fileList) => {
  console.log(response);

  imgUrl.value = response.imgUrl
  form.value.imgUrl = imgUrl.value;
}
let form = ref([])

const edit = async (id: number) => {
  console.log(id)
  const res = await fetchGoodsList({
    currentPage: 1,
    pageSize: 100,
  })
  form.value = res.data.filter((ele) => ele.id === id)[0]
  fileList.value = [
    {
      name: form.name,
      url: `http://127.0.0.1:5000/upload/imgs/goods_img/${form.value.imgUrl}`,
    },
  ]

  dialogFormVisible.value = true
}

const handleSizeChange = async (val: number) => {
  console.log(val)

  const res = await fetchGoodsList({
    currentPage: 1,
    pageSize: val,
  })
  tableData.value = res.data
}
const handleCurrentChange = async (val: number) => {
  const res = await fetchGoodsList({
    currentPage: val,
    pageSize: pageSize4.value,
  })
  tableData.value = res.data
}

const open = (id: number) => {
  ElMessageBox.confirm('此操作将永久删除该条数据，是否继续?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      //删除的逻辑
      const res = await fetchGoodsDel({ id })
      handleSizeChange(pageSize4.value)
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

const confirmEdit = async () => {
  const data = {
    name: form.value.name,
    category: form.value.category,
    price: form.value.price,
    imgUrl: form.value.imgUrl,
    goodsDesc: form.value.goodsDesc,
    id: form.value.id,
  }
  const res = await fetchGoodsEdit(data)

  fileList.value = [
    {
      name: form.value.name,
      url: `http://127.0.0.1:5000/upload/imgs/goods_img/${imgUrl.value}`,
    },
  ]

  handleSizeChange(pageSize4.value)
  dialogFormVisible.value = false
}

onMounted(async () => {
  const res = await fetchGoodsList({
    currentPage: 1,
    pageSize: pageSize4.value,
  })
  tableData.value = res.data
  const res1 = await fetchGoodsCategories()
  categories.value = res1
})
</script>

<style scoped>
#goods-list {
  width: 100%;
  height: 90%;
  overflow-y: scroll;
}
img {
  width: 40%;
  background-size: cover;
}
</style>
